package com.example.demo.Interceptor;

import com.example.demo.util.IdThreadLocal;
import com.example.demo.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    RedisTemplate redisTemplate;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (request.getMethod().equals("OPTIONS")){
            return true;
        }
        String token=request.getHeader("Token");
        System.out.println(token);

        if (token==null  ){
            throw new RuntimeException("no login");
        }
        else {
            String id=tokenUtil.verify(token).toString();
            System.out.println(id);
            ValueOperations valueOperations=redisTemplate.opsForValue();
            String o = (String) valueOperations.get(id);
            System.out.println(o);
            if (o!=null && o.equals(token)){
                throw new RuntimeException("no loginhh");
            }

            //threadlocal添加用户的id
           else {
                IdThreadLocal.put(tokenUtil.verify(token));
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        IdThreadLocal.remove();
    }
}
